var route;
var markers = new Array();
var map;
var mediaPoints = new Object();
var geocoder = new google.maps.Geocoder();

var default_center = new google.maps.LatLng(44, -86);
var default_zoom = 3;
$(document).ready(function() {
	var myOptions = {
			zoom: default_zoom,
			center: default_center,
            mapTypeId: google.maps.MapTypeId.SATELLITE
	};
	
	map = new google.maps.Map(document.getElementById("map"), myOptions);
    loadWalks();
});

function plotWalk(guid) { 
	clearMap();
   	route = new google.maps.Polyline({
        strokeColor: "#ff6600",
        strokeOpacity: 1.0,
        strokeWeight: 4
    });

	$.getJSON("rest/query/points/"+guid,
		function(data) {
			if ( data ) {
            	var path = route.getPath();
				var bounds = new google.maps.LatLngBounds();
				var it;
				if ( $.makeArray(data.point).length == 1 ) {
					it = data;
				} else {
					it = data.point;
				}
				$.each(it, function(i, point) {
					var point = new google.maps.LatLng(point.lat, point.lon);
					path.push(point);
					bounds.extend(point);
				});
		
				route.setMap(map);
				map.fitBounds(bounds);
			} else { 
				alert("There were no points associated with this walk.");
			}

			$.getJSON("rest/query/files/"+guid, 
				function(data) {
					if ( data ) { 
						var it;
						if ( $.makeArray(data.file).length == 1 ) {
							it = data;
						} else {
							it = data.file;
						}
						
						$.each(it, function(i, file) {
							var point = new google.maps.LatLng(file.lat, file.lon);
							if ( !mediaPoints[point.toUrlValue()] ) {	
					            createMarker(i, file, point);
					            var arr = new Array();
					            arr.push(file);
					            mediaPoints[point.toUrlValue()] = arr;
							} else {
								mediaPoints[point.toUrlValue()].push(file);
							}
						});
					}
			});
		}
	);  
}

function clearMap(reset) {
	if ( route) { route.setMap(null); }
	$.each(markers, function(i, marker) { marker.setMap(null); });
	markers = new Array();
	mediaPoints = new Object();

	$("#upload").show();
	$("#mediafiles").empty();
	
	if ( reset ) {
		map.setCenter(default_center);
		map.setZoom(default_zoom);
	}
}

function createMarker(i, data, point) {
	var marker = new google.maps.Marker({
		position: point,
		map: map,
		title: "An audio recording",
		icon: 'http://google-maps-icons.googlecode.com/files/amphitheater.png'
	});
	
	markers.push(marker);
    google.maps.event.addListener(marker, 'click', function () {
    	 $("#upload").hide();
    	 $("#mediafiles").empty();

    	 $.each(mediaPoints[point.toUrlValue()], function(i, file) {
    		 /* I really should be creating this using DOM objects and not text */
    		var html = "<div class=\"row\">";
    		html += "<audio src=\"rest/query/file/"+file.guid+"\" controls=\"controls\">";
    		html += "You need an HTML compaitable browser to access the functionality.";
    		html += "</audio>";
    		html += "<h3>Sample taken near <span id=\"loc"+file.guid+"\"></span></h3>";
    		html += "<table><tr><td>Host:</td><td>Specimen:</td></tr>";
    		html +=	"<tr><td><input value=\""+file.host+"\" id=\""+file.guid+"host\" type=\"text\"/></td>";
    		html += "<td><input value=\""+file.specimen+"\" id=\""+file.guid+"specimen\"type=\"text\"/></td></tr>";
    		html += "<tr><td colspan=\"2\">";
    		html += "Comments:<br/><textarea id=\""+file.guid+"comments\" style=\"width: 100%;\" cols=\"10\" rows=\"5\">"+file.comments+"</textarea></td></tr>";
    		html += "<tr><td><span id=\""+file.guid+"response\"></span></td><td style=\"text-align: right;\"><input type=\"button\" class=\"fancy2\" value=\"Update\" onclick=\"updateFile('"+file.guid+"', '"+file.rowId.trim()+"')\"/></td></tr></table>";
    		html += "</div>";
    		$("#mediafiles").append(html);
    		
			geocoder.geocode( { 'latLng': new google.maps.LatLng(file.lat, file.lon)}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					$("#loc"+file.guid).append(results[0].formatted_address);
				}
			});
    	 });
     });
}

function updateFile(guid,rowid) {
    $("#"+guid+"response").empty();
	$("#"+guid+"response").append("Updating the file ...");
    
	var service_str = "rest/gpx/file/update?rowid=";
	service_str += rowid;
	service_str += "&host="+$("#"+guid+"host").val();
	service_str += "&specimen="+$("#"+guid+"specimen").val();
	service_str += "&comments="+$("#"+guid+"comments").val();
	
	$.ajax({
		  url: service_str,
		  type: "PUT",
		  success: function(data) {
	    	$("#"+guid+"response").empty();		
		    $("#"+guid+"response").append("The file has been updated.");
		  },
		  error: function() {
			  $("#"+guid+"response").empty();
			  $("#"+guid+"response").append("The file was not updated.");
		  }
	});
}

function loadWalks() { 
	$.getJSON("rest/query/walks",
		function(data) {
			if ( data ) {
				var it;
				if ( $.makeArray(data.walk).length == 1 ) {
					it = data;
				} else {
					it = data.walk;
				}
				
				$.each(it, function(i,walk) {
					var str = "<td><a href=\"javascript:plotWalk('"+walk.guid+"')\">"+walk.name+"</a></td>";
					str += "<td>"+walk.description+"</td>";
					str += "<td>"+walk.walker+"</td>";
					str += "<td>"+walk.date+"</td>";
					$("#walks").append("<tr>"+str+"</tr>");					
				});
				
				$("#walks").append("<tr><td style=\"padding-top: 20px;\" colspan=\"4\"><a href=\"javascript:clearMap(true)\">Clear the Map</a></td></tr>");
				
			} else { 
				alert("The Fusion Tables do not contain any walks.");
			}
		}
	);
}